<template>
  <div class="container">
    <el-row :gutter="10" class="row">
      <el-col :span="8">
        <el-card class="table-card time-line">
          <el-timeline>
            <el-timeline-item
              v-for="work in sortedTaskList"
              :key="work.id"
              :timestamp="parseTime(work.updatedAt, '{y}-{m}-{d}')"
              placement="top"
            >
              <el-card class="timeline-card">
                <div class="timeline-header">
                  <h4>更新项目：{{ work.title }}</h4>
                  <div class="tag-container">
                    优先级：
                    <dict-tag :options="dict.type.priority" :value="work.priority"/>
                    状态：
                    <dict-tag :options="dict.type.work_status" :value="work.status"/>
                  </div>
                </div>
                <p class="timeline-footer">
                  <user-and-avatar :user-id="work.updatedBy"/>
                  提交于 {{
                    parseTime(work.updatedAt, '{y}-{m}-{d}')
                  }}
                </p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card class="table-card">
          <div>
            <el-calendar v-if="works">
              <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
              <template
                slot="dateCell"
                slot-scope="{data}">
                  <span :class="data.isSelected ? 'is-selected' : ''" class="date-text">{{ data.day.split('-').slice(1).join('-') }}</span>
                  <dict-tag
                    v-if="calendar.get(parseTime(data.day, '{y}-{m}-{d}'))"
                    :options="dict.type.priority"
                    :value="calendar.get(parseTime(data.day, '{y}-{m}-{d}'))"
                    class="priority-tag"
                  />
              </template>
            </el-calendar>
          </div>

        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="10" class="row">
      <el-col :span="12">
        <el-card class="table-card">
          代办统计
          <div id="workItem" :style="myChartStyle"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="table-card">
          代办列表
          <el-table @row-click="(row)=>{showWorkInit=true;nowWork=row;workId=row.workItemId}" :data="getNoOkWork" border height="350">
            <el-table-column label="所属项目" align="center" prop="projectId"/>
            <el-table-column label="任务标题" align="center" prop="title"/>
            <el-table-column label="优先级" align="center" prop="priority">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.priority" :value="scope.row.priority"/>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" prop="status">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.work_status" :value="scope.row.status"/>
              </template>
            </el-table-column>
            <el-table-column label="开始日期" align="center" prop="startDate" width="170">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="截止日期" align="center" prop="dueDate" width="170">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.dueDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      title="详情"
      :visible.sync="showWorkInit"
      width="1650px">
      <work-item :work-id="workId"></work-item>
    </el-dialog>
  </div>
</template>

<script>
import {listMyAllWork} from "@/api/projectUser/userWork";
import UserAndAvatar from "@/components/UserAndAvatar/index.vue";
import * as echarts from "echarts";
import WorkItem from "@/components/Project/workItem.vue";


export default {
  name: "Index",
  components: {WorkItem, UserAndAvatar},
  dicts: ['work_status', 'actual_value', 'work_type', 'priority', 'requirement_type', 'work_risk'],
  data() {
    return {
      workId:null,
      myChartStyle: {float: "left", width: "100%", height: "358px"}, //图表样式
      works: null,
      showWorkInit: false,
      nowWork: {},
      calendar:new Map()
    };
  },
  created() {
    this.getData();
  },
  mounted() {

  },
  computed: {
    sortedTaskList() {
      if (!this.works) return [];
      return this.works
        .filter(work => work.createdAt) // 确保有创建时间
        .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt)); // 按时间倒序
    },
    getNoOkWork(){
      return (this.works||[]).filter(work=>work.status!=='3')
    }
  },
  methods: {
    initEchartsWorkItem() {
      // 获取所有工作类型并计算有效类型（排除全0类型）
      const allWorkTypes = Array.from(new Set(this.works.map(item => item.type)));
      const validWorkTypes = allWorkTypes.filter(type => {
        // 计算该类型在所有状态下的总数
        return this.works.some(work => work.type === type)
      });

      // 生成系列数据（自动过滤无效类型）
      const worksData = this.dict.type.work_status.map(status => {
        const data = validWorkTypes.map(type =>
          this.works.filter(work =>
            work.type === type && work.status === status.value
          ).length
        );

        return {
          name: status.label,
          type: 'bar',
          stack: 'total',
          label: {
            show: true,
            formatter: ({value}) => value > 0 ? value : '' // 隐藏0值标签
          },
          emphasis: {
            focus: 'series'
          },
          data
        };
      });

      // 生成图表配置
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'shadow'}
        },
        legend: {},
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        yAxis: {type: 'value'},
        xAxis: {
          type: 'category',
          data: validWorkTypes.map(type =>
            (this.dict.type.work_type.find(item => item.value === type) || {label: type}).label
          )
        },
        series: worksData
      };

      // 初始化图表
      echarts.init(document.getElementById('workItem')).setOption(option);
    },
    getData() {
      listMyAllWork({}).then(res => {
        this.works = res.data;
        this.works.forEach(work => {
          if (work.status !== "completed" && work.status !== "close"&&work.dueDate) {
            console.log(!this.calendar[work.dueDate]);
            if(!this.calendar.get(work.dueDate)||(this.calendar.get(work.dueDate)<work.priority)){
              this.calendar.set(work.dueDate,work.priority)
            }
          }
        })
        this.initEchartsWorkItem()
        console.log(this.calendar);
      });
    }
  }
};
</script>

<style scoped lang="scss">
.time-line {
  overflow-y: auto;
  padding-right: 10px;
}

.row {
  margin-bottom: 10px;
}

.table-card {
  height: 390px;
  padding: 5px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  }
}

// 日历样式重写
::v-deep .el-calendar {
  .el-calendar__header {
    padding: 12px 20px;
    border-bottom: 1px solid #ebeef5;
    background-color: #f8f9fa;
  }

  .el-calendar__title {
    color: #303133;
    font-weight: 600;
  }

  .el-calendar-table {
    .el-calendar-day {
      height: 40px;
      padding: 4px;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: space-between;

      &:hover {
        background-color: #f5f7fa;
      }
      .date-text {
        flex-shrink: 0;
        margin-right: 8px;
      }

      .priority-tag {
        margin-left: auto;
        flex-shrink: 0;
      }
    }

    .el-calendar-day.is-selected {
      background-color: #ecf5ff;
    }

  }
}

.dateGrid {
  height: 100%;
  padding: 4px;
}

.container {
  padding: 10px;
  width: 100%;
}

.flex-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  padding: 0 4px;
  border-radius: 4px;
  transition: all 0.3s ease;

  &:hover {
    background-color: rgba(64, 158, 255, 0.1);
  }
}

.left-content {
  font-size: 14px;
  color: #606266;
}


.is-selected {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: 500;
}

.timeline-card {
  margin-bottom: 8px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;

  h4 {
    margin: 0;
    font-size: 15px;
    color: #303133;
  }
}

.tag-container {
  display: flex;
  gap: 8px;
  align-items: center;
  font-size: 13px;
  color: #606266;
}

.timeline-footer {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 8px;
}

// 表格样式优化
::v-deep .el-table {
  font-size: 13px;

  th {
    background-color: #f8f9fa !important;
    color: #606266;
    font-weight: 600;
  }

  td {
    padding: 8px 0;
  }

  .el-table__row {
    transition: all 0.3s ease;

    &:hover {
      background-color: #f5f7fa;
    }
  }
}

// 图表容器样式
#workItem {
  margin-top: 20px;
  border-radius: 4px;
  background: #fff;
}
</style>

